﻿using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Indicies
{
    /// <summary>
    /// Command to wrap the SQL required to add a foreign key to a table.
    /// </summary>
    public static class AddCommand
    {
        private const string Sql = "CREATE {0} INDEX {1} ON {2} ({3}{4});";

        /// <summary>
        /// Executes a command to add a foreign key to a table.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="connection">The connection.</param>
        public static void Execute(Index index, Connection connection)
        {
            if (!ExistsCommand.Execute(index, connection))
            {
                var indexType = index.IndexType.ToString().ToUpper();

                if (indexType == "DEFAULT") indexType = string.Empty;

                var indexLength = string.Format("({0})", index.Length);

                if (indexLength == "(0)") indexLength = string.Empty;

                connection.ExecuteNonQuery(Sql, null,
                                            indexType,
                                            index.Name,
                                            index.Table,
                                            index.Column,
                                            indexLength);
            }
        }
    }
}